package com.itheima.web.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获得到token
        String token = request.getHeader("Authorization");
        //删除前缀
        token = token.replace("Bearer " , "");
        //2.校验redis中是否有这个key
        String redisJson = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        if(redisJson == null){ //过期了
            //throw new BusinessException("登录状态已过期");
            response.setStatus(401);//权限不足
            return false;
        }
        //3.解析token -> 转换admin
        Map map = JwtUtil.parseToken(token);
        //转换admin
        Admin admin = BeanUtil.mapToBean(map, Admin.class, false);

        if(admin == null){
            response.setStatus(401);//权限不足
            return false;
        }

        //4.将admin绑定到线程中
        AdminHolder.set(admin);
        //5.续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token , "1" , Duration.ofMinutes(30));
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();//解除线程绑定
    }
}
